package com.tyk.bookstore.back.product.mq;

import com.rabbitmq.client.Channel;
import com.tyk.bookstore.back.common.mq.RabbitManager;
import com.tyk.bookstore.back.product.model.enume.BookState;
import com.tyk.bookstore.back.product.service.BookService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author tyk
 * @description BookMqReceiver
 */
@Service
@RequiredArgsConstructor
public class BookMqReceiver {

    /**
     * 消息唯一标识的key
     */
    @Value("${mine.mq.rabbit.id-key}")
    private String idKey;


    /**
     * 默认重试次数
     */
    @Value("${mine.mq.rabbit.retry}")
    public int retryCount;

    /**
     * 重试次数的key
     */
    @Value("${mine.mq.rabbit.args.retry-count}")
    private String retryCountKey;

    private final BookService bookService;
    private final RabbitManager rabbitManager;

    /**
     * 定时发布书籍
     *
     * @param bookId  书籍ID
     * @param msg     消息
     * @param channel 通道
     */
    @SneakyThrows
    @RabbitListener(queues = BookMqConstant.BOOK_RELEASE_QUEUE)
    public void receiveDelayMsg(Long bookId, Message msg, Channel channel) {
        MessageProperties ps = msg.getMessageProperties();
        try {
            // 上架书籍
            bookService.changeBookStatus(bookId, BookState.ON);
        } catch (Exception e) {

            // 写日志，通知维护人员
            System.out.println("书籍上架失败, bookId=" + bookId);

            // 查看是否可以重试
            int count = this.retryCount;
            String rcs = ps.getHeader(this.retryCountKey);
            if (rcs != null) count = Integer.parseInt(rcs);

            // 转非延迟消息进行重试
            if (count > 0) {
                rabbitManager.sendMsg(
                        ps.getReceivedExchange(),
                        ps.getReceivedRoutingKey(),
                        bookId,
                        ps.getHeader(this.idKey),
                        Map.of(
                                BookMqConstant.ARGS_MEMBER_ID, ps.getHeader(BookMqConstant.ARGS_MEMBER_ID),
                                this.retryCountKey, String.valueOf(--count)
                        )
                );
            } else {
                System.out.println("书籍上架重试失败, bookId=" + bookId);
            }
        }
        // 确认消息已被消费
        // 无论是否成功处理，此消息确已被消费者成功接收
        channel.basicAck(ps.getDeliveryTag(), false);
    }

}
